package controllers

/**
 * Created by yz on 2017/5/31.
 */

import command.CommandExec
import dao.{BoxplotDataDao, ModeDao}
import play.api.mvc._
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import javax.inject.Inject
import implicits.Implicits._
import shared.Pojo._
import tool.Pojo.CommandData
import upickle.default._

import scala.concurrent.ExecutionContext.Implicits.global

class ExploreController @Inject()(cc: ControllerComponents)(
  implicit val modeDao: ModeDao,
  implicit val boxplotDataDao: BoxplotDataDao
) extends AbstractController(cc) {

  def getFileData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.dataDir, data.fileName)
    val lines = file.nameSuffix match {
      case "txt" => file.txtLines
      case "csv" => file.csvLines
      case "xlsx" => file.xlsxLines()
    }
    val (map, array) = Utils.getInfoByLines(lines)
    val response = GetFileData.Response(map = map, array = array)
    Ok(writeJs(response))
  }

  def getBoxplotImage = Action.async { implicit request =>
    val startTime = System.currentTimeMillis()
    val data = FormTool.geneNameForm.bindFromRequest().get
    val geneSymbol = data.geneName
    boxplotDataDao.selectAll(geneSymbol).map { rows =>
      val tmpDir = Tool.createTempDirectory("tmpDir")
      val pdfFile = new File(tmpDir, "out.pdf")
      val pngFile = new File(tmpDir, "out.png")
      val inputFile = new File(tmpDir, "input.csv")
      val headers = List("celltype", "Med", "AvgExpr", "Q25", "Q75", "Min", "Max", "Freq", "gene")
      val lines = rows.map { row =>
        List(row.cellType, row.med, row.avgExpr, row.q25, row.q75, row.min, row.max, row.freq, row.gene)
      }.toList
      (headers :: lines).toFile(inputFile)
      val colorFile = new File(Tool.dataDir, "pal1.txt")
      val command =
        s"""
           |${"Rscript".condaPath()} ${Tool.rPath.unixPath}/boxplot.R --i ${inputFile.unixPath} --c ${colorFile.unixPath} --s ${data.geneName}  --o ${pdfFile.unixPath}
           |convert  -density 300 -background white -alpha remove -alpha off ${pdfFile.getAbsoluteFile.unixPath} ${pngFile.getAbsoluteFile.unixPath}
           |""".stripMargin
      val commandExec = CommandExec().exec { b =>
        CommandData(tmpDir, command)
      }
      val response = if (commandExec.isSuccess) {
        println("bar exec complete:", Utils.getTime(startTime))
        val base64 = pngFile.base64
        GetImageResponse(valid = true, base64 = base64)
      } else {
        GetImageResponse(valid = false, message = commandExec.errorInfo)
      }
      Tool.deleteDirectory(tmpDir)
      Ok(writeJs(response))
    }

  }

}
